<script setup lang="ts">
import {
  getStudentPage,
  getUserForm,
  deleteUsers,
  // addStudent,
  updateUser,
  // getProjectForm,
  // updateProject,
  // addProject,
  deleteProjects,
} from "@/api/userinfo/user/index";
import {
  UserPageVO,
  UserForm,
  StudentQuery,
  Project,
} from "@/api/userinfo/user/types";
import { UploadRawFile, UploadRequestOptions } from "element-plus";
import { uploadFileApi } from "@/api/file";
import { Plus, CloseBold } from "@element-plus/icons-vue";
import { useUserStore } from "@/store/modules/user";

const { user } = useUserStore();

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); //用户表单

const addView = ref(true); //添加按钮是否可视
const viewDialog = ref(false); //判断是否为查看
const loading = ref(false); //加载状态
const queryParams = reactive<StudentQuery>({
  page: 1,
  pageSize: 10,
});
const enrollmentYear = ref("");
const total = ref(0); // 数据总数
const pageData = ref<UserPageVO[]>(); // 用户分页数据

watch(enrollmentYear, (newVal) => {
  if (newVal) {
    queryParams.enrollmentYear = newVal;
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<UserForm>({ projectList: [] });
//新增项目表单数据
const createProject = (): Project => {
  return {
    projectName: "",
    time: "",
    introduction: "",
    progress: "",
  };
};

const rules = reactive({
  image: [{ required: true, trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入电话号码", trigger: "blur" },
    { pattern: /^\d{11}$/, message: "请输入正确的电话号码", trigger: "blur" },
  ],
  email: [{ required: true, message: "请输入邮箱地址", trigger: "blur" }],
  officeId: [
    { required: true, message: "请输入学院名称", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
      message: "学院名称只能包含中文字符、字母和数字",
      trigger: "blur",
    },
  ],
  major: [
    { required: true, message: "请输入专业名称", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
      message: "专业名称只能包含中文字符、字母和数字",
      trigger: "blur",
    },
  ],
  enrollmentYear: [
    {
      required: true,
      message: "请选择入学时间",
      trigger: "blur",
    },
  ],
  skills: [{ required: true, message: "请输入技能特长", trigger: "blur" }],
  hobby: [{ required: true, message: "请输入爱好", trigger: "blur" }],
  honor: [{ required: true, message: "请输入获得的荣誉", trigger: "blur" }],
  innovationExp: [
    {
      required: true,
      message: "请输入与创业或创新相关的经历和成果",
      trigger: "blur",
    },
  ],
  projectName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  time: [{ required: true, message: "请选择时间", trigger: "blur" }],
  introduction: [
    { required: true, message: "请输入项目简介", trigger: "blur" },
  ],
  progress: [{ required: true, message: "请输入项目进展", trigger: "blur" }],
});
/** 查询 */
function handleQuery() {
  loading.value = true;
  getStudentPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  enrollmentYear.value = "";
  queryParams.page = 1;
  queryParams.enrollmentYear = undefined;
  handleQuery();
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户查看：user-view
 * @param id 用户ID
 */
function openDialog(type: string, id?: string) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "user-form") {
    // 用户表单弹窗
    if (id) {
      dialog.title = "修改用户";
      getUserForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
      });
      console.log(formData);

      // getProjectForm(id).then(({ data }) => {
      //   Object.assign(formData, { ...data });
      // });
    } else {
      dialog.title = "新增用户";
      formData.projectList = [createProject()];
    }
  } else if (dialog.type === "user-view" && id) {
    // 用户查看弹窗
    getUserForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
    });
    // getProjectForm(id).then(({ data }) => {
    //   Object.assign(formData, { ...data });
    // });
    viewDialog.value = true;
    dialog.title = "用户信息";
  }
}
const newProject = () => {
  formData.projectList?.push(createProject());
};
const removeProject = (index: number) => {
  formData.projectList?.slice(index, 1);
};

/**
 * 关闭弹窗
 *
 * @param
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
  viewDialog.value = false;
  formData.image = "";
  formData.projectList = [];
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (dialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const userId = formData.id;
        loading.value = true;
        if (userId) {
          ElMessageBox.confirm("确认修改用户？", "警告", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }).then(async function () {
            const description = user?.roles[0]?.description;
            if (description == "管理员" || description == "超级管理员") {
              await updateUser(formData)
                .then(() => {
                  ElMessage.success("修改用户成功");
                  closeDialog();
                  resetQuery();
                })
                .finally(() => (loading.value = false));
            }
          });
        }
        // else {
        //   console.log(formData);

        //   ElMessageBox.confirm("确认增添用户？", "警告", {
        //     confirmButtonText: "确认",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(async function () {
        //     await addStudent(formData, 1)
        //       .then(() => {
        //         ElMessage.success("新增用户成功");
        //         closeDialog();
        //         resetQuery();
        //       })
        //       .finally(() => (loading.value = false));
        //   });
        // }
      }
    });
  } else if (dialog.type === "user-view") {
    closeDialog();
  }
}, 3000);

/** 删除用户 */
function handleDelete(id?: string) {
  if (id) {
    ElMessageBox.confirm("确认删除用户?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function (id) {
      console.log(id);
      deleteUsers(id).then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      });
    });
  }
}

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue"]);
const imgUrl = useVModel(props, "modelValue", emit);

/**
 * 自定义图片上传
 *
 * @param options
 */
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  const fileInfo = await uploadFileApi(options.file); // 调用你的上传接口
  const img = fileInfo.msg;
  formData.image = img;
}

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于2M");
    return false;
  }
  return true;
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- 学生列表 -->
    <div class="search-container">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
        label-width="100px"
        class="form-container"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            placeholder="姓名"
            clearable
            style="width: 200px"
            pror="name"
            v-model="queryParams.name"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学院" prop="officeId">
          <el-input
            placeholder="学院"
            v-model="queryParams.officeId"
            @keyup.enter="handleQuery"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input
            placeholder="专业"
            v-model="queryParams.major"
            @keyup.enter="handleQuery"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input
            placeholder="手机号码"
            v-model="queryParams.phone"
            @keyup.enter="handleQuery"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            placeholder="邮箱"
            v-model="queryParams.email"
            @keyup.enter="handleQuery"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="入学年份">
          <el-date-picker
            v-model="enrollmentYear"
            class="!w-[200px]"
            type="year"
            placeholder="开始年份"
            value-format="YYYY"
            clearable
          />
        </el-form-item>
        <el-form-item class="handleQuery">
          <!-- @click="handleQuery" -->
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <!-- @click="resetQuery" -->
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between" v-show="addView">
          <el-button type="success" @click="openDialog('user-form')"
            ><i-ep-plus />新增</el-button
          >
        </div>
      </template>

      <el-table v-loading="loading" :data="pageData" style="width: 100%">
        <el-table-column label="姓名" width="120" align="center" prop="name" />

        <el-table-column
          label="学院"
          align="center"
          width="200"
          prop="officeId"
        />

        <el-table-column label="专业" align="center" width="200" prop="major" />

        <el-table-column
          label="入学时间"
          align="center"
          prop="enrollmentYear"
          width="180"
        />

        <el-table-column
          label="手机号码"
          align="center"
          prop="phone"
          width="150"
        />

        <el-table-column label="邮箱" align="center" width="250" prop="email" />

        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <!-- v-hasPerm="['sys:user:reset_pwd']"自定义命令，查看用户是否有使用该功能的权限 -->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog('user-view', scope.row.userId)"
              ><i-ep-view />查看</el-button
            >
            <el-button
              type="primary"
              link
              size="small"
              @click="openDialog('user-form', scope.row.userId)"
              ><i-ep-edit />编辑</el-button
            >

            <el-button
              type="primary"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <template #title>
        <div style="font-size: 22px; font-weight: bold">{{ dialog.title }}</div>
      </template>
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form :rules="rules">
          <el-form-item label="学生照片" prop="image">
            <!-- 上传组件 -->
            <el-upload
              v-model="formData.image"
              class="single-uploader"
              :show-file-list="false"
              list-type="picture-card"
              :before-upload="handleBeforeUpload"
              :http-request="uploadFile"
            >
              <img
                v-if="formData.image"
                :src="formData.image"
                class="single-uploader__image"
              />
              <el-icon v-else class="single-uploader__icon"
                ><i-ep-plus
              /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-form-item label="姓名" prop="name">
          <el-input
            placeholder="请输入姓名"
            v-model="formData.name"
            :disabled="viewDialog"
            >姓名</el-input
          >
        </el-form-item>
        <h3>联系方式</h3>
        <el-form-item label="电话号码" prop="phone">
          <el-input
            placeholder="请输入电话号码"
            v-model="formData.phone"
            :disabled="viewDialog"
            >电话号码</el-input
          >
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            placeholder="请输入邮箱地址"
            v-model="formData.email"
            :disabled="viewDialog"
            >邮箱</el-input
          >
        </el-form-item>
        <h3>个人信息</h3>
        <el-form-item label="学院" prop="officeId">
          <el-input
            placeholder="请输入学院"
            v-model="formData.officeId"
            :disabled="viewDialog"
            >学院</el-input
          >
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input
            placeholder="请输入专业"
            v-model="formData.major"
            :disabled="viewDialog"
            >专业</el-input
          >
        </el-form-item>
        <el-form-item label="入学时间" required prop="enrollmentYear">
          <el-date-picker
            v-model="formData.enrollmentYear"
            style="width: 100%"
            type="year"
            placeholder="选择时间"
            value-format="YYYY"
            :disabled="viewDialog"
            clearable
          />
        </el-form-item>
        <h3>个人简介</h3>
        <el-form-item label="技能/特长" prop="skills">
          <el-input
            :rows="3"
            type="textarea"
            placeholder="请输入技能特长"
            v-model="formData.skills"
            :disabled="viewDialog"
            >技能/特长</el-input
          >
        </el-form-item>
        <el-form-item label="爱好" prop="hobby">
          <el-input
            :rows="3"
            type="textarea"
            placeholder="请输入爱好"
            v-model="formData.hobby"
            :disabled="viewDialog"
            >爱好</el-input
          >
        </el-form-item>
        <el-form-item label="获得的荣誉" prop="honor">
          <el-input
            :rows="2"
            type="textarea"
            placeholder="请输入获得的荣誉"
            v-model="formData.honor"
            :disabled="viewDialog"
            >获得的荣誉</el-input
          >
        </el-form-item>
        <el-form-item label="经历和成果" prop="innovationExp">
          <el-input
            :rows="3"
            type="textarea"
            placeholder="请输入与创业或创新相关的经历和成果"
            v-model="formData.innovationExp"
            :disabled="viewDialog"
            >与创业或创新相关的经历和成果</el-input
          >
        </el-form-item>
        <h3 class="projectTitle">项目简介</h3>
        <el-button
          @click="newProject()"
          style="margin-bottom: 5px"
          size="small"
          type="primary"
        >
          <el-icon><Plus /></el-icon>
        </el-button>
        <div
          v-for="(project,index) in formData.projectList as any"
          :key="index"
          style="
            display: flex;
            align-items: start;
            justify-content: space-between;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
          "
        >
          <div style="flex-grow: 1">
            <el-form-item
              label="项目名称"
              :prop="`projectList[${index}].projectName`"
            >
              <el-input
                placeholder="请输入项目名称"
                v-model="project.projectName"
                :disabled="viewDialog"
                >项目名称</el-input
              >
            </el-form-item>
            <el-form-item label="项目时间" :prop="`projectList[${index}].time`">
              <el-date-picker
                v-model="project.time"
                type="date"
                style="width: 100%"
                palceholder="开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="viewDialog"
              />
            </el-form-item>
            <el-form-item
              label="项目简介"
              :prop="`projectList[${index}].introduction`"
            >
              <el-input
                :rows="3"
                type="textarea"
                placeholder="请输入项目简介"
                v-model="project.introduction"
                :disabled="viewDialog"
                >项目简介</el-input
              >
            </el-form-item>
            <el-form-item
              label="项目进展"
              :prop="`projectList[${index}].progress`"
            >
              <el-input
                placeholder="请输入项目进展"
                v-model="project.progress"
                :disabled="viewDialog"
                >项目进展</el-input
              >
            </el-form-item>
          </div>
          <el-button
            text
            circle
            style="margin-left: 10px"
            @click="removeProject(index)"
            ><el-icon><CloseBold /></el-icon
          ></el-button>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 认</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.form-container {
  display: flex;
  flex-wrap: wrap;
}

.handleQuery {
  margin-left: auto;
}

.time {
  margin: 0 10px;
}

.projectTitle {
  display: inline;
  margin-right: 24px;
}

.single-uploader {
  overflow: hidden;
  cursor: pointer;
  border: 1px var(--el-border-color) solid;
  border-radius: 6px;

  &:hover {
    border-color: var(--el-color-primary);
  }

  &__image {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: contain; /* 这会保持图片的纵横比，同时让图片完全适应容器 */
  }

  &___icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
</style>
